package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @FileName DeviceDataServiceImpl
 * @Description
 * @Author Sword
 * @date 2025-10-12
 **/

@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, deviceId);

        Device device = deviceMapper.selectOne(queryWrapper);

        if (ObjectUtil.isEmpty(device)) {
            log.error("设备不存在");
            return;
        }

        //获取到设备上报的数据
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            //获取上报属性
            Map<String, Object> properties = service.getProperties();

            if (ObjectUtil.isEmpty(properties)) {
                return;
            }

            //处理上报时间
            LocalDateTime eventTime = LocalDateTimeUtil
                    .parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'")
                    .atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            List<DeviceData> list = new ArrayList<>();

            properties.forEach((key, value) -> {
                DeviceData deviceData = DeviceData.builder()
                        .iotId(deviceId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(eventTime)
                        .dataValue(value + "")
                        .build();


                list.add(deviceData);
            });

            //保存数据
            saveBatch(list);

            //将设备数据缓存到redis
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(list));

        });


    }

    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto) {

        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page(dto.getPageNum(), dto.getPageSize());
        //模糊查询设备名称
        if (StringUtils.isNotEmpty(dto.getDeviceName())) {
            lambdaQueryWrapper.eq(DeviceData::getDeviceName, dto.getDeviceName());
        }
        //精确查询功能名称
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        //时间范围查询
        if (ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime())) {
            lambdaQueryWrapper.between(DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());
        }

        //分页查询
        page = page(page, lambdaQueryWrapper);

        //封装分页对象
        return getTableDataInfo(page);

    }

    /**
     * 封装分页对象
     *
     * @param page
     * @return
     */
    private static TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
}
